package org.net5ijy.security.dao.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.net5ijy.security.bean.User;
import org.net5ijy.security.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * UserDaoImpl
 *
 * @author XGF
 * @date 2020/11/30 22:42
 */
@Repository
public class UserDaoImpl implements UserDao {

  @Autowired
  private SessionFactory sessionFactory;

  @Override
  public void saveUser(User user) {
    this.sessionFactory.getCurrentSession().save(user);
  }

  @Override
  public void deleteUser(Integer id) {
    Session session = this.sessionFactory.getCurrentSession();
    User u = (User) session.load(User.class, id);
    session.delete(u);
  }

  @Override
  public void updateUser(User user) {
    this.sessionFactory.getCurrentSession().merge(user);
  }

  @Override
  public User getUser(Integer id) {
    return (User) this.sessionFactory.getCurrentSession().get(User.class,
        id);
  }

  @Override
  public User getUser(String username) {
    Query query = this.sessionFactory.getCurrentSession().createQuery(
        "from User where username = ?");
    query.setParameter(0, username);
    return (User) query.uniqueResult();
  }

  @Override
  public User getUserByMobile(String mobile) {
    Query query = this.sessionFactory.getCurrentSession().createQuery(
        "from User where mobile = ?");
    query.setParameter(0, mobile);
    return (User) query.uniqueResult();
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<User> getUsers() {
    Query query = this.sessionFactory.getCurrentSession().createQuery(
        "from User");
    return query.list();
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<User> getUsers(int page, int size) {
    Query query = this.sessionFactory.getCurrentSession().createQuery(
        "from User");
    int startRow = (page - 1) * size;
    query.setFirstResult(startRow);
    query.setMaxResults(size);
    return query.list();
  }

  @Override
  public int count() {
    Query query = this.sessionFactory.getCurrentSession().createQuery(
        "select count(*) from User");
    Number count = (Number) query.uniqueResult();
    return count.intValue();
  }
}
